import os
import django
import random
import sys
from datetime import datetime, timedelta

# 设置Django环境 - 必须在导入任何Django模型之前
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'deep_test.settings')
django.setup()

# 现在可以安全地导入Django模型
from django.utils import timezone
from exam_system.models import ExamRoom, Subject

def create_test_exam_room():
    """创建一个测试考场，状态为preparing"""
    # 检查是否已存在准备中的考场
    existing = ExamRoom.objects.filter(status='preparing').first()
    if existing:
        print(f"已存在准备中的考场：{existing.name}，ID：{existing.id}")
        return existing

    # 获取一个科目，如果没有则创建
    subject = Subject.objects.first()
    if not subject:
        subject = Subject.objects.create(name="测试科目", code="TEST")
        print(f"创建了新科目：{subject.name}")

    # 创建考场
    now = timezone.now()
    start_time = now + timedelta(minutes=5)  # 5分钟后开始
    end_time = start_time + timedelta(minutes=60)  # 考试时长60分钟

    exam_room = ExamRoom.objects.create(
        name=f"测试考场-{random.randint(1000, 9999)}",
        subject=subject,
        description="这是一个用于测试Celery任务的考场",
        start_time=start_time,
        end_time=end_time,
        duration=60,  # 60分钟
        total_score=100,
        pass_score=60,
        status='preparing',
        is_published=True,
        created_by_id=1  # 假设ID为1的用户是管理员
    )

    print(f"成功创建测试考场：{exam_room.name}，ID：{exam_room.id}")
    print(f"考试开始时间：{start_time.strftime('%Y-%m-%d %H:%M:%S')}")
    return exam_room

if __name__ == '__main__':
    create_test_exam_room()